﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Linq;

namespace SP.SPProject.Core.Support
{
    public class DataAccess<C,E>
        where C : DataContext, new()
    {
        private string _entitySet;

        public DataAccess(string entitySet)
        {
            _entitySet = entitySet;
        }

        public EntityList<E> GetAll()
        {
            using (C context = new C())
            {
                return context.GetList<E>(_entitySet);
            }
        }

        public IEnumerable<E> GetFiltered(Func<E, bool> filter)
        {
            using (C context = new C())
            {
                return getQueryObject(context).Where(filter);
            }
        }

        public void Add(E newItem)
        {
            using (C context = new C())
            {
                getQueryObject(context).InsertOnSubmit(newItem);
                context.SubmitChanges();
            }
        }

        public void Update(E entity)
        {
            using (C context = new C())
            {
                var queryObject = getQueryObject(context);
                queryObject.Attach(entity);
                context.SubmitChanges();
            }
        }

        private EntityList<E> getQueryObject(C context)
        {
            return context.GetList<E>(_entitySet);
        }

    }
}
